#include "KeyframeController.h"

Keyframe::Keyframe(float position, float time)
:_position(position), _time(time)
{}

KeyframeController::KeyframeController()
:m_easyinout(false)
{
	m_time.init(this, 0);
	registerDependent(&m_time);
}

KeyframeController::~KeyframeController()
{
	for(vector<Keyframe*>::iterator i = m_keyframeList.begin(); i != m_keyframeList.end(); i++)
	{
		if( *i != 0)
		{
			delete *i;
			*i = 0;
		}
	}
}

void KeyframeController::addKeyframe(Keyframe* s)
{
	unsigned int i=0;
	bool add=false;

	// if i < to the size of the vector and the keyframe has not been added
	while (i < m_keyframeList.size() && add==false)
	{
		//if the time of the keyframe in the vector is > to the time of the new keyframe
		if(m_keyframeList[i]->_time > s->_time )
		{
			m_keyframeList.insert(m_keyframeList.begin()+i, s);
			add=true;
		}
		i++;
	}
	//if the keyframe has not been added we put it in the end of the vector
	if(add==false)
	{
		m_keyframeList.push_back( s );
	}
}

void KeyframeController::doUpdate()
{
	float s=0;
	float p=0;
	unsigned int i=0;
	bool found = false;
	

	if (m_time>= m_keyframeList[0]->_time && m_time<m_keyframeList[m_keyframeList.size()-1]->_time)
	{
		while(i<m_keyframeList.size() && found==false)
		{
			if(m_keyframeList[i]->_time>m_time)
			{
				found=true;
			}
			else
			{
				i++;
			}
		}
		//i is now the index of the second keyframe
		s = (m_time-m_keyframeList[i-1]->_time)/(m_keyframeList[i]->_time-m_keyframeList[i-1]->_time);
		if(m_easyinout==true)
		{
			s=3*s*s-2*s*s*s;
		}
		p = m_keyframeList[i-1]->_position + (m_keyframeList[i]->_position-m_keyframeList[i-1]->_position)*s;
		setValue(p);
	}
}